//在mobx中 所有的state都会存在类里面 mobx用类去表达一个"store"
//1.observable 用于把数据变成"可观察"的数据类型
import { observable, action, configure, runInAction, computed } from 'mobx';
import { getProduct } from './api';
//2.action用于更新state 更新state的唯一方式
//action.bound 让当前action函数的this永久指向当前(Store)的实例

//3.强制使用action
// configure({
//   enforceActions:"observed"
// })
//4.computed计算属性
configure({
  enforceActions: 'observed',
});

class Store {
  @observable num = 520;
  @observable msg = '你是吃啥长大的';
  @observable product = [];
  @observable cart = [];
  // @action incrementAction() {

  // }
  // @action decrementAction(tem) {

  // }
  @action.bound fetchProduct() {
    getProduct('./data/index.json')
      .then(body => body.json())
      .then(res => {
        console.log(res);
        runInAction(() => {
          this.product = res;
        });
      });
  }

  @action addCart(item) {
    let res = this.product.data.find(ele => ele.id === item.id);
    if (res.inventory === 0) return false;
    if (res) {
      res.inventory--;
    }
    let target = this.cart.find(ele => ele.id === item.id);
    if (target) {
      target.count++;
    } else {
      runInAction(() => {
        item.count = 1;
        this.cart = [...this.cart, item];
      });
    }
  }
  @action delCart(item) {
    let res = this.product.data.find(ele => ele.id === item.id);
    if (res) {
      res.inventory++;
    }
    let target = this.cart.find(ele => ele.id === item.id);
    if (target) {
      target.count--;
    }
  }
  @action del(item) {
    let res = this.cart.filter(ele => ele.id !== item.id);
    let res2 = this.cart.find(ele => ele.id === item.id);
    let res1 = this.product.data.find(ele => ele.id === item.id);
    if (res1) {
      // console.log(res.count);
      res1.inventory += res2.count;
    }
    this.cart = [...res];
  }
  @computed get total() {
    let sum = 0;
    for (let i = 0; i < this.cart.length; i++) {
      sum += this.cart[i].price * this.cart[i].count;
    }
    return sum;
  }
}
export default new Store();
